<?php

namespace App\Models;


/**
 * 系统公告对象
 */
class MRoles extends BaseModel
{
    public $table = "roles";

    //表关系区===========================================================================


    /**
     * 新增或编辑一个角色
     * @param $request
     * @param $id
     * @return bool
     */
    public static function SaveOrCreateRole($request)
    {
        $role = MRoles::find($request->id);
        if (empty($role)) {
            if (Admin::existRoles($request)) {
                return json_encode(['code' => 1, 'msg' => '该角色已存在！']);
            }
            $roles = new MRoles();
            $roles->name = $request->name;
            $roles->description = $request->description;
            $roles->created_at = time();
            $roles->slug = str_random(16);
            $roles->level = 1;
            $role_save = $roles->save();
            $permission_role = new MPermissionRoles();
            $permission_role->role_id = MRoles::where('name', $request->name)->first()->id;
            $permission_role->permissions = serialize(json_decode($request->permissions));
            $permission_role->created_at = time();
            $per_role_save = $permission_role->save();
            if ($role_save && $per_role_save) {
                return true;
            } else {
                return false;
            }
        } else {
            $role->name = $request->name;
            $role->description = $request->description;
            $role->updated_at = time();
            $role_save = $role->save();
            $permission_role = MPermissionRoles::where('role_id', $request->id)->first();
            $permission_role->permissions = serialize(json_decode($request->permissions, true));
            $permission_role->updated_at = time();
            $per_role_save = $permission_role->save();
        }
        if ($role_save && $per_role_save) {
            return true;
        } else {
            return false;
        }
    }
}